package load

import (
	"apidoc2entity/model"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	"sync"
	"xorm.io/core"
)

var x *xorm.Engine

func DbRead() []model.BuilderPackage {
	var err error
	x, err = xorm.NewEngine("mysql", "root:123456@tcp(localhost:30306)/information_schema?charset=utf8mb4")
	//设置日志显示
	x.ShowSQL(true)
	x.SetLogLevel(core.LOG_DEBUG)
	if err != nil {
		fmt.Printf("数据库连接失败:", err)
	}
	var ss []model.BuilderStruct
	in := PickerPump("union-busi")
	// FAN-OUT
	c1 := MakeStruct(in)
	c2 := MakeStruct(in)
	c3 := MakeStruct(in)
	// consumer
	for s := range Merge(c1, c2, c3) {
		ss = append(ss, *s)
	}

	fmt.Println(ss)
	return nil
}

func PickerPump(dbStr string) <-chan *model.BuilderStruct {
	var sts []model.BuilderStruct
	x.Table("TABLES").
		Select("TABLE_SCHEMA,TABLE_NAME,TABLE_COMMENT").
		Where("table_schema =?", dbStr).Find(&sts)
	out := make(chan *model.BuilderStruct)
	go func() {
		defer close(out)
		for _, s := range sts {
			out <- &s
		}
	}()
	return out
}

func MakeStruct(stch <-chan *model.BuilderStruct) <-chan *model.BuilderStruct {
	out := make(chan *model.BuilderStruct)
	go func() {
		defer close(out)
		for st := range stch {
			var fields []model.BuilderField
			table_schema := "union-busi"
			table_name := "busi_base_merchant"
			x.Table("COLUMNS").
				Select("TABLE_SCHEMA,TABLE_NAME,COLUMN_NAME,DATA_TYPE,CHARACTER_MAXIMUM_LENGTH,COLUMN_COMMENT").
				Where("table_schema =? And TABLE_NAME=?", table_schema, table_name).Find(&fields)
			st.BFields = fields
			//组装数据
			out <- st
		}
	}()
	return out
}

func Merge(chs ...<-chan *model.BuilderStruct) <-chan *model.BuilderStruct {
	out := make(chan *model.BuilderStruct)
	var wg sync.WaitGroup
	collect := func(in <-chan *model.BuilderStruct) {
		defer wg.Done()
		for n := range in {
			out <- n
		}
	}
	wg.Add(len(chs))
	// FAN-IN
	for _, c := range chs {
		go collect(c)
	}
	// 正确方式
	go func() {
		wg.Wait()
		close(out)
	}()
	return out
}
